<script lang="ts" setup>
import type { NodeDetails } from '@/apis/model/node'
import { Message } from '@arco-design/web-vue'
import {
  deleteCdnWafNodeUnbindApi,
  getCdnNodeWafsApi,
  getNodeDetailApi,
} from '@/apis/modules/cdn'
// import type { WafListItem } from '@/apis/model/waf'
// import { getApiNodeApi } from '@/apis/modules/node/node'
import { wafCustomOptions, wafStrategyOptions } from '@/constants/cdn-node'
import { useConfigStore } from '@/stores/config'
import { getOptionsLabel } from '@/utils/cdn'
import { commonTableProps } from '@/utils/table'
import DeployRules from './components/DeployRules.vue'
import RuleDetails from './components/RuleDetails.vue'
import useConfig from './useConfig'

const route = useRoute()

const queryParams = ref<any>({
  scope: 3,
  order: 'asc',
  sort: 'priority',
  // sort: 'created_at',
  action: 0,
})

const moduleType = ref(3)
const { searchSchema, columns } = useConfig(moduleType)
const { visible: deployVisible, open: openDeploy } = usePopup()
const { visible, open: openDrawer, data: detailData } = usePopup<WafListItem>()
const nodeDetails = ref<NodeDetails>()

const { data, loading, run, pagination } = useListRequest(getCdnNodeWafsApi, {
  params: queryParams,
  immediate: false,
})
function handleModuleChange(v: number | string | boolean) {
  queryParams.value = {
    ...queryParams.value,
    module: v as number,
  }
  queryParams.value.action = 0
  useConfigStore().getCondition({ module: v })
  run()
}
function handleDelete(row: any) {
  ModalHelper.error({
    title: '移除规则',
    content: `确认从节点移除规则 “${row?.name}” ？`,
    okText: '移除',
    width: 480,
    closable: false,
    onOk: async () => {
      await deleteCdnWafNodeUnbindApi({
        node_id: route.params.id,
        module: moduleType.value,
        waf_ids: [row.id],
      })
      await run()
      Message.success('删除成功')
    },
  })
  // CloudModal.error(
  //   {
  //     content: `确认从节点移除规则 “${row?.name}” ？`,
  //     okText: '移除',
  //   },
  //   async () => {
  //     await deleteWafNodeUnbindApi({
  //       id: route.params.id as string,
  //       module: moduleType.value,
  //       waf_ids: [row?.id],
  //     })
  //     ToastUtils.success('操作成功')
  //     run!()
  //   },
  // )
}
const nodeName = ref('')
function getNodeInfo() {
  // 获取节点信息
  getNodeDetailApi({ id: queryParams.value.bind_node_id }).then((res) => {
    const node = res.node!
    nodeDetails.value = node
    nodeName.value = node.name
  })
}
watch(moduleType, () => {
  queryParams.value.action = 0
})
watch(
  () => route.params.id,
  (v) => {
    if (v) {
      queryParams.value.bind_node_id = v as string
      queryParams.value.module = moduleType.value
      getNodeInfo()
      run()
    }
  },
  {
    immediate: true,
  },
)

onMounted(async () => {
  await nextTick()
  const logModule = localStorage.getItem('logModule')
  if (logModule) {
    const customRulesId = localStorage.getItem('customRulesId')
    queryParams.value.id = customRulesId
    moduleType.value = Number(logModule)
    queryParams.value.module = moduleType.value
    localStorage.setItem('logModule', '')
    localStorage.setItem('customRulesId', '')
    run()
  }

  // params.value.start_time = dayjs(
  //   dayjs().subtract(60, 'minute').format('YYYY-MM-DD HH:mm:ss')
  // ).unix()
  // params.value.end_time = dayjs(dayjs().format('YYYY-MM-DD HH:mm:ss')).unix()
  // tableHeader()
  // run()
})
</script>

<template>
  <main-container
    :pagination="pagination"
    :loading="loading"
    @run="run"
  >
    <template #title>
      <a-breadcrumb class="main-container__breadcrumb">
        <a-breadcrumb-item>
          <router-link :to="{ name: 'CdnNodeNodeList' }">
            节点列表
          </router-link>
        </a-breadcrumb-item>
        <a-breadcrumb-item class="text-12px">
          {{ nodeName }}
        </a-breadcrumb-item>
      </a-breadcrumb>
    </template>
    <template #header-prefix />
    <div class="mt-24px" />
    <div class="mb-4">
      <div
        v-if="nodeDetails?.group?.type === 2"
        class="mb-6"
      >
        <a-alert
          type="warning"
          class="border-radius-8px mb-6 !bg-[#FFEAE8]"
        >
          <span class="text-12px">当前节点分组为上游组，安全配置不生效。</span>
        </a-alert>
      </div>
      <div class="mb-6">
        <a-radio-group
          v-model="moduleType"
          type="button"
          @change="handleModuleChange"
        >
          <a-radio :value="3">
            白名单
          </a-radio>
          <a-radio :value="1">
            自定义规则
          </a-radio>
          <a-radio :value="2">
            速率规则
          </a-radio>
        </a-radio-group>
      </div>

      <section class="flex items-center gap-x-4">
        <a-button
          type="primary"
          @click="openDeploy"
        >
          部署规则
        </a-button>
        <a-select
          v-if="[1, 2].includes(moduleType)"
          v-model="queryParams.action"
          class="!w-[136px]"
          :options="
            moduleType === 1
              ? [{ label: '全部执行策略', value: 0 }, ...wafCustomOptions]
              : moduleType === 2
                ? [{ label: '全部执行策略', value: 0 }, ...wafStrategyOptions]
                : []
          "
          @change="run"
        />
        <multiple-condition-search
          v-model="queryParams"
          :schema="searchSchema"
          @search="run"
        />
        <a-button
          class="ml-auto shrink-0 text-color-1"
          type="outline"
          :disabled="loading"
          @click="run"
        >
          <template #icon>
            <i-icons-refresh :class="{ 'animate-spin': loading }" />
          </template>
        </a-button>
      </section>
    </div>

    <div
      style="height: calc(100vh - 400px); overflow: auto"
      class="mt-2"
    >
      <div class="h-full">
        <a-table
          v-bind="commonTableProps"
          :columns="columns"
          :data="data"
        >
          <template #strategy="{ record }">
            <div class="flex items-center gap-x-6px">
              <i-icons-prevent v-if="record.action === 1" />
              <i-icons-observe v-if="record.action === 3" />

              <i-icons-js v-if="record.action === 4" />
              <i-icons-inquiry v-if="record.action === 5" />
              <span>{{
                getOptionsLabel(wafCustomOptions, record.action)
              }}</span>
            </div>
          </template>

          <template #action="{ record }">
            <a-link
              :hoverable="false"
              @click="openDrawer(record)"
            >
              <i-icons-eye size="16px" />
            </a-link>
            <a-link
              :hoverable="false"
              status="danger"
              @click="handleDelete(record)"
            >
              <i-icons-delete size="16px" />
            </a-link>
          </template>
        </a-table>
      </div>
    </div>
    <rule-details
      v-model="visible"
      :type="moduleType"
      :rule-id="detailData?.id ?? ''"
    />
    <deploy-rules
      v-if="deployVisible"
      v-model:visible="deployVisible"
      :type="moduleType"
      @refresh="run"
    />
  </main-container>
</template>

<style lang="less" scoped>
:deep(.arco-radio-group-button) {
  border-radius: var(--border-radius-lg, 8px);
  .arco-radio-button {
    border-radius: var(--border-radius-lg, 6px);
  }
}
:deep(.arco-alert-warning) {
  display: flex;
  padding: 6px 8px 6px 16px;
  align-items: flex-start;
  //gap: 8px;
  align-self: stretch;
  border-radius: 8px;
  background: var(--danger-1, #ffeae8);
  .arco-alert-icon {
    svg {
      color: #ff4d4f;
    }
  }
}
</style>
